﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Mail;
using EPiAbstractions;
using EPiAbstractions.Community.Blog;
using EPiServer.Common;
using EPiServer.Community.Blog;
using EPiServer.Community.Modules;
using EPiServer.Core;
using JoelAbrahamsson.BlogExtensions;
using JoelAbrahamsson.PageTypes;

namespace JoelAbrahamsson.SubscriptionNotification
{
    public class CommentSubscribersNotifierModule : IModule
    {
        public string UniqueName
        {
            get { return typeof(CommentSubscribersNotifierModule).FullName; }
        }

        public string AdministrationControl
        {
            get { return string.Empty; }
        }

        public string Name
        {
            get { return "CommentSubscribersNotifierModule"; }
        }

        public void OnApplicationStart(EPiServer.Community.CommunityContext context)
        {
            BlogHandlerFacade.Instance.EntryCommentAdded += Instance_EntryCommentAdded;
        }

        void Instance_EntryCommentAdded(string sender, EPiServerCommonEventArgs e)
        {
            EntryComment addedComment = (EntryComment)e.Object;
            
            IList<IAuthor> subscribers = addedComment.Entry.GetSubscribers();
            Start startPage = (Start) DataFactoryFacade.Instance.GetPage(PageReference.StartPage);
            SmtpClient smtpClient = new SmtpClient();
            foreach (IAuthor subscriber in subscribers)
            {
                MailMessage message = new MailMessage("noreply@joelabrahamsson.com", subscriber.Email);
                message.Subject = string.Format("{0} has commented on {1}", addedComment.Author.Name, addedComment.Entry.Title);
                message.Body = startPage.CommentNotificationEmailTemplate;
                message.Body = message.Body.Replace("{recipientName}", subscriber.Name);
                message.Body = message.Body.Replace("{entryTitle}", addedComment.Entry.Title);
                message.Body = message.Body.Replace("{entryUrl}", addedComment.Entry.GetUrl()));
                smtpClient.Send(message);
                message.IsBodyHtml = true;

                smtpClient.Send(message);
            }
        }
    }
}
